import Vue from 'vue'
import Vuex from 'vuex'
import { getPasswords, addPassword, updatePassword, deletePassword } from '@/common/api.js'
import { encrypt, decrypt, generateKey } from '@/common/crypto.js'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    passwords: [],
    masterKey: null
  },
  mutations: {
    setPasswords(state, passwords) {
      state.passwords = passwords
    },
    setMasterKey(state, key) {
      state.masterKey = key
    }
  },
  actions: {
    async fetchPasswords({ commit, state }) {
      const encryptedData = await getPasswords()
      const decrypted = encryptedData.map(item => {
        return {
          ...item,
          password: decrypt(item.password, state.masterKey)
        }
      })
      commit('setPasswords', decrypted)
    },
    
    async addNewPassword({ commit, state }, item) {
      const encryptedItem = {
        ...item,
        password: encrypt(item.password, state.masterKey),
        id: Date.now().toString()
      }
      await addPassword(encryptedItem)
      this.dispatch('fetchPasswords')
    },
    
    initializeSecurity({ commit }, secret) {
      const masterKey = generateKey(secret)
      commit('setMasterKey', masterKey)
    }
  }
})

export default store